
#import "Card_Game.h"
#import "SimpleAudioEngine.h"
#import "GameConfig.h"
#import "AppController.h"

@implementation RecordItem 

- (id)initRecord:(NSString *)pName 
	  RecordFlag:(NSString *)pRecordFlag
	   RecordNum:(NSString *)pRecordNum
		   frame:(CGRect)pFrame 
{
	self = [super initWithFrame:pFrame];
	{
		[self setUserInteractionEnabled:NO];
		
		//背景人物框
		RecordBg = [[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"人物框.png"]] autorelease];
					 
		//奖牌
		UIImage * pFlagImg = [UIImage imageNamed:pRecordFlag];
		RecordFlag = [[[UIImageView alloc]initWithImage:pFlagImg] autorelease];
		[RecordFlag setFrame:CGRectMake(5, (pFrame.size.height - pFlagImg.size.height)/2,pFlagImg.size.width,pFlagImg.size.height)];
		
		//玩家名字
		RecordPlayer = [[[UILabel alloc]initWithFrame:CGRectMake(40,16,80,26)] autorelease];
		RecordPlayer.text = pName;
		RecordPlayer.textColor = [UIColor whiteColor];
		RecordPlayer.backgroundColor = [UIColor clearColor];
		RecordPlayer.font = [UIFont fontWithName:@"Arial" size:25];
		
		//玩家分数
		UIImage * pNumImg = [UIImage imageNamed:pRecordNum];
		RecordNum = [[[UIImageView alloc]initWithImage:pNumImg] autorelease];
		if(pNumImg.size.width > 30)
		{
			[RecordNum setFrame:CGRectMake(115,(pFrame.size.height - pNumImg.size.height)/2 - 3,pNumImg.size.width,pNumImg.size.height)];
		}
		else
		{
			[RecordNum setFrame:CGRectMake(122,(pFrame.size.height - pNumImg.size.height)/2 - 3,pNumImg.size.width,pNumImg.size.height)];
		}
		
		//点
		UIImage * pPointImg = [UIImage imageNamed:@"点.png"];
		RecordTextPoint = [[[UIImageView alloc]initWithImage:pPointImg] autorelease];
		[RecordTextPoint setFrame:CGRectMake(152,(pFrame.size.height - pPointImg.size.height)/2 + 2,pPointImg.size.width,pPointImg.size.height)];
		
		[self addSubview:RecordBg];
		[self addSubview:RecordFlag];
		[self addSubview:RecordPlayer];
		[self addSubview:RecordNum];
		[self addSubview:RecordTextPoint];
	}
	return self;
}

@end

@implementation Card_Game


@synthesize nTotalPlayer;

-(void)onEnter
{
	// 节点调用init方法以后将会调用此方法
	// 如果使用了CCTransitionScene,将会在过渡效果开始以后调用此方法
	[super onEnter];
	NSLog(@"onEnter");
}

-(void)onEnterTransitionDidFinish
{
	// 调用onEnter以后将会调用此方法
	// 如果使用了CCTransitionScene,将会在过渡效果结束以后调用此方法
	[super onEnterTransitionDidFinish];
	NSLog(@"onEnterTransitionDidFinish");
	if(isResultView)
	{
		[m_pScrollView setHidden:NO];
	}
}

-(void)onExit
{
	// 节点调用dealloc方法之前将会调用此方法 
	// 如果使用了CCTransitionScene,将会在过渡效果结束以后调用此方法
	[super onExit];
	NSLog(@"onExit");
}

+(CCScene *) scene
{
	// 'scene' is an autorelease object.
	CCScene *scene = [CCScene node];
	
	// 'layer' is an autorelease object.
	Card_Game *layer = [Card_Game node];
	
	// add layer as a child to scene
	[scene addChild: layer];
	
	// return the scene
	return scene;
}

- (void) dealloc
{
	[m_pScrollView release];
	
	[super dealloc];
}

-(id)init:(id<Card_GameDelegate>) _delegate;
{
	self = [super init];
	if (self)
	{
		AppController * app = (AppController*)[[UIApplication sharedApplication] delegate];
		
		delegate = _delegate;
		
		//CGSize size = [[CCDirector sharedDirector] winSize];
		
		m_pScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0,62,320,373)];
		
		[m_pScrollView setHidden:YES];
		
		[app.window addSubview:m_pScrollView];
		
		//背景
		/*
		CCSprite *sp = [CCSprite spriteWithFile:@"bg.png"];
		//sp.rotation = 90;
		sp.position = ccp(size.width/2, size.height/2);
		[self addChild:sp z:0 tag:1];
		*/

		
		[self getPlayerInfo];
		
		//玩家
//		labelPlayer = [CCLabelTTF labelWithString:@"玩家1" fontName:@"Marker Felt" fontSize:32];
//		labelPlayer.color = ccBLUE;
//		labelPlayer.position =  ccp( size.width/2 , 450);
//		[self addChild:labelPlayer z:0 tag:CARD_GAME_PLAYER];
		
		//牌面精灵
//		CCMenuItem *spCardBack = [CCMenuItemImage itemFromNormalImage:@"card_back.png" 
//													   selectedImage:@"card_back.png" 
//															  target:self 
//															selector:@selector(startSelectCard)];
//		spCardBack.position = ccp(size.width/2,260);
//		menuCardBack = [CCMenu menuWithItems:spCardBack, nil];
//		menuCardBack.position = CGPointZero;
//		//menuCardBack.tag = E_BASE_LEFT_ARROW_ICON;
//		[self addChild:menuCardBack];
//		
//		//倒计时精灵
//		spCountDown = [CCSprite spriteWithFile:@"num0.png"];
//		spCountDown.position = ccp(size.width/2, 80);
//		[self addChild:spCountDown z:0 tag:CARD_GAME_SP_COUNT_DOWN];
		
		//OK
		[CCMenuItemFont setFontName:@"Arial"];
		[CCMenuItemFont setFontSize:25];
		
//		selectedMenu = [CCMenuItemFont itemFromString:@"就选这张" target:self selector:@selector(OnSelectedOK:)];
//		selectedMenu.position = ccp(size.width/2, 30);
//		
//		CCMenu *menu = [CCMenu menuWithItems:selectedMenu, nil];
//		menu.position = CGPointZero;
//		[self addChild:menu z:1 tag:CARD_GAME_SP_SELECTED_OK];
		
		///////////////////////////////////////////////////////////
		//底部背景
		bottomBg=[CCSprite spriteWithFile:@"bottom_bg.png"];
		bottomBg.position = ccp(SCREEN_WIDTH/2,BOTTOM_HEIGHT);
		[self addChild:bottomBg];
		
		//确定
		//CCMenuItem *startMenu = [CCMenuItemFont itemFromString:@"开始游戏"	target:self selector:@selector(Card_Menu_Play:)];
		CCMenuItemImage * selectedMenu = [CCMenuItemImage itemFromNormalImage:@"Btn_SelectedOK.png" selectedImage:@"Btn_SelectedOK_down.png" target:self selector:@selector(OnSelectedOK:)];
		mn = [CCMenu menuWithItems:selectedMenu,  nil];
		mn.position = ccp(SCREEN_WIDTH/2,BOTTOM_HEIGHT);
		[self addChild:mn z:1 tag:2];
		
		//返回
		CCMenuItemImage *vm = [CCMenuItemImage itemFromNormalImage:@"back_icon.png" selectedImage:nil target:self selector:@selector(Card_Game_Return:)];
		CCMenu *vmm = [CCMenu menuWithItems: vm, nil];
		vmm.position = ccp(BOTTOM_X, BOTTOM_HEIGHT);
		[self addChild:vmm z:2];
		
		//help
		
		CCMenuItemImage *help = [CCMenuItemImage itemFromNormalImage:@"help_icon.png" selectedImage:nil target:self selector:@selector(Card_Game_Des:)];	
		CCMenu *helpMenu = [CCMenu menuWithItems: help, nil];
		helpMenu.position = ccp(SCREEN_WIDTH - BOTTOM_X , BOTTOM_HEIGHT);
		[self addChild:helpMenu z:2];
		
		
		///////////////////////////////////////////////////////////
		scoreArray = [[NSMutableArray alloc] init];
		cardArray = [[NSMutableArray alloc] init];
		
		for (int i=0; i<54; i++)
		{
			[cardArray addObject:[NSNumber numberWithInt:i+1]];
		}
		
		//允许touch事件
		self.isTouchEnabled = YES;
		
		//多线程队列
		//self.queue = [[NSOperationQueue alloc] init];
		
		nCurPlayer   = 0;
		nCurCardNum  = 0;
		isGameOver   = NO;
		isResultView = NO;
		
		
		[self startPlayer];
		
		//[self doubleMusicPlay:@"music.mp3"];
		
	}
	
	return self;
}

//开始游戏
-(void)startPlayer
{
	[self unschedule:@selector(startPlayer)];
	CGSize size = [[CCDirector sharedDirector] winSize];
	
	//menuCardBack.visible = NO;
//	//牌面精灵
//	if (!menuCardBack) {
//		CCMenuItem *spCardBack = [CCMenuItemImage itemFromNormalImage:@"card_back.png" 
//														selectedImage:@"card_back.png" 
//															   target:self 
//															 selector:@selector(startSelectCard)];
//		spCardBack.position = ccp(size.width/2,260);
//		menuCardBack = [CCMenu menuWithItems:spCardBack, nil];
//		menuCardBack.position = CGPointZero;
//		//menuCardBack.tag = E_BASE_LEFT_ARROW_ICON;
//		[self addChild:menuCardBack];
//	}
//	else {
//		menuCardBack.visible = YES;
//	}


	

	//玩家
	if (!labelPlayer)
	{
		labelPlayer = [CCLabelTTF labelWithString:[NSString stringWithFormat:@"%@",[playerNameArray objectAtIndex:0]] fontName:@"Arial" fontSize:32];
		labelPlayer.color = ccWHITE;
		labelPlayer.position =  ccp( size.width/2 , 430);
		[self addChild:labelPlayer z:0 tag:CARD_GAME_PLAYER];
	}
	else
	{
		nCurPlayer++;
		[labelPlayer setString:[NSString stringWithFormat:@"%@",[playerNameArray objectAtIndex:nCurPlayer]]];
	}

	//随机选牌
//	int index = 0;
//	while (nCurCardNum != (index=[(NSNumber*)[cardArray objectAtIndex:arc4random()%[cardArray count]] intValue]))
//	{
//		nCurCardNum = index;
//		
//		//[self spriteSetTexture:spCard ImageFile:[NSString stringWithFormat:@"%d.jpg",nCurCardNum]];
//	}
	//牌面精灵
	if (!spCard)
	{
		spCard=[CCSprite spriteWithFile:@"card_back.png"];//[NSString stringWithFormat:@"%d.png",nCurCardNum]];//@"1.jpg"];
		spCard.position = ccp(size.width/2,260);
		[self addChild:spCard z:0 tag:CARD_GAME_SP_CARD];
	}
	else
	{
		//[self spriteSetTexture:spCard ImageFile:@"1.jpg"];
		[self spriteSetTexture:spCard ImageFile:@"card_back.png"];//[NSString stringWithFormat:@"%d.png",nCurCardNum]];
	}
	isCardBack = YES;
	selectedMenu.visible = NO;
	
	if (!spNextCard)
	{
		spNextCard= [CCSprite spriteWithFile:@"card_back.png"];//[NSString stringWithFormat:@"%d.png",nCurCardNum]];//@"1.jpg"];
		spNextCard.position = ccp(size.width/2,260);
		[self addChild:spNextCard];
		spNextCard.visible = NO;
	}
	if (!spImage)
	{
		spImage= [CCSprite spriteWithFile:@"card_back.png"];//[NSString stringWithFormat:@"%d.png",nCurCardNum]];//@"1.jpg"];
		spImage.position = ccp(size.width/2,260);
		[self addChild:spImage];
		spImage.visible = NO;
	}
	

	
	//倒计时按钮背景
	if (!spCountBg) {
		spCountBg=[CCSprite spriteWithFile:@"计时器.png"];
		spCountBg.position = ccp(size.width/2,120);
		[self addChild:spCountBg];
	}

	if (!labelCountNum) {
		labelCountNum = [CCLabelTTF labelWithString:@"10" fontName:@"Arial" fontSize:24];
		labelCountNum.color = ccWHITE;
		labelCountNum.position =  ccp( size.width/2 , 120);
		[self addChild:labelCountNum];
	}
	else {
		[labelCountNum setString:@"10"];
	}


	
	//倒计时精灵
//	if (!spCountDown)
//	{
//		spCountDown = [CCSprite spriteWithFile:@"num1.png"];
//		spCountDown.position = ccp(size.width/2, 80);
//		[self addChild:spCountDown z:0];
//		
//		if (!spCountDown1) {
//			spCountDown1 = [CCSprite spriteWithFile:@"num0.png"];
//			spCountDown1.position = ccp(size.width/2+15, 80);
//			[self addChild:spCountDown1 z:0 tag:CARD_GAME_SP_COUNT_DOWN];
//		}
//
//	}
//	else
//	{
//		[self spriteSetTexture:spCountDown ImageFile:@"num1.png"];
//		spCountDown1.visible = YES;
//	}

//	nLeftSeconds = 10;
//	[self schedule:@selector(countDown) interval:1.0];
}

-(void)startSelectCard
{
	CGSize size = [[CCDirector sharedDirector] winSize];
	selectedMenu.visible = YES;
	
	[labelCountNum setString:@"10"];
	
	//随机选牌
	int index = 0;
	while (nCurCardNum != (index=[(NSNumber*)[cardArray objectAtIndex:arc4random()%[cardArray count]] intValue]))
	{
		nCurCardNum = index;
		
		//[self spriteSetTexture:spCard ImageFile:[NSString stringWithFormat:@"%d.jpg",nCurCardNum]];
	}
	//牌面精灵
	if (!spCard)
	{
		spCard=[CCSprite spriteWithFile:[NSString stringWithFormat:@"%d.png",nCurCardNum]];//@"1.jpg"];
		spCard.position = ccp(size.width/2,260);
		[self addChild:spCard z:0 tag:CARD_GAME_SP_CARD];
	}
	else
	{
		//[self spriteSetTexture:spCard ImageFile:@"1.jpg"];
		[self spriteSetTexture:spCard ImageFile:[NSString stringWithFormat:@"%d.png",nCurCardNum]];
	}
	
	nLeftSeconds = 10;
	[self schedule:@selector(countDown) interval:1.0];
	//[self startPlayer];
	//menuCardBack.visible = NO;
}

#pragma mark Item Action
//确认选择
-(void)OnSelectedOK:(id)sender
{
	AppController * app = (AppController*)[[UIApplication sharedApplication] delegate];
	
	[app TipSound];
	
	if (isCardBack) //背面
		return;
	
	[self unschedule:@selector(countDown)]; //停止计时器
	
	NSLog(@"CardNum: %d",nCurCardNum);
	[scoreArray addObject:[NSNumber numberWithInt:nCurCardNum]];//[NSString stringWithFormat:@"%d",nCurCardNum]];
	[cardArray removeObject:[NSNumber numberWithInt:nCurCardNum]];
	
	
	if (nCurPlayer == nTotalPlayer - 1) //gameover
	{
		isResultView = YES;
		[self schedule:@selector(gameOver) interval:0.1];
		//[self gameOver];
	}
	else if (nCurPlayer < nTotalPlayer-1)
	{
		[self startPlayer];
		//menuCardBack.visible = YES;
	}
	
}

//倒计时
-(void)countDown
{
	isGameOver = NO;
	nLeftSeconds--;
	//spCountDown1.visible = NO;
	if (nLeftSeconds == 0)
	{
		[self unschedule:@selector(countDown)];
		[scoreArray addObject:[NSNumber numberWithInt:nCurCardNum]];//[NSString stringWithFormat:@"%d",nCurCardNum]];
		[cardArray removeObject:[NSNumber numberWithInt:nCurCardNum]];
		
		//isGameOver = YES;
		
		if (nCurPlayer == nTotalPlayer - 1) //gameover
		{
			isGameOver = YES;
			[self schedule:@selector(gameOver) interval:0.5];
			//[self gameOver];
		}
		else if (nCurPlayer < nTotalPlayer-1)
		{
			[self startPlayer];
			//[self schedule:@selector(startPlayer) interval:1.0f];
			//menuCardBack.visible = YES;
		}
	}
	else
		[labelCountNum setString:[NSString stringWithFormat:@"%d",nLeftSeconds]];
	//[self spriteSetTexture:spCountDown ImageFile:[NSString stringWithFormat:@"num%d.png",nLeftSeconds]];
	
}

//游戏结束
-(void)gameOver
{
	[self unschedule:@selector(gameOver)];
	
	isResultView = YES;
	
	NSMutableDictionary *dir=[[NSMutableDictionary alloc] initWithCapacity:nTotalPlayer];
	for (int i=0; i<nTotalPlayer; i++)//NSString *strName in playerNameArray)
	{
		NSLog(@"%@,key:%@",[playerNameArray objectAtIndex:i],[scoreArray objectAtIndex:i]);
		[dir setObject:[playerNameArray objectAtIndex:i] forKey:[scoreArray objectAtIndex:i]];
	}
	
	
	CGSize size = [[CCDirector sharedDirector] winSize];
	NSArray *sortArray=[scoreArray sortedArrayUsingSelector:@selector(compare:)];
	for (int i=0; i<nTotalPlayer; i++)//NSString *strName in playerNameArray)
	{
		NSLog(@"sort:player:%@,score:%d",[playerNameArray objectAtIndex:i],[[sortArray objectAtIndex:nTotalPlayer-i-1] intValue]);
		//[dir setObject:[playerNameArray objectAtIndex:i] forKey:[sortArray objectAtIndex:i]];
	}
	
	//移除当前精灵，显示结果
	[self removeChild:labelPlayer cleanup:YES];
	[self removeChild:spCard cleanup:YES];
	//[self removeChild:spCountDown cleanup:YES];
	//[self removeChild:menuCardBack cleanup:YES];
	//[self removeChild:selectedMenu cleanup:YES];
	[self removeChild:mn cleanup:YES];
	[self removeChild:spCountBg cleanup:YES];
	[self removeChild:labelCountNum cleanup:YES];
	
	//[self spriteSetTexture:bottomBg ImageFile:@"按钮背景.png"];
	[selectedMenu setVisible:NO];
	
	CCMenuItemImage *punishment = [CCMenuItemImage itemFromNormalImage:@"接受惩罚.png" selectedImage:@"接受惩罚_down.png" target:self 
															  selector:@selector(OnNextStep:)];
	mn = [CCMenu menuWithItems:punishment,  nil];
	mn.position = ccp(SCREEN_WIDTH/2,BOTTOM_HEIGHT);
	[self addChild:mn z:1 tag:2];
	
	///////////////////////////////////////////////////
	
	CCSprite *spScoreTitle=[CCSprite spriteWithFile:@"score_title.png"];
	spScoreTitle.position = ccp(size.width/2,442);
	[self addChild:spScoreTitle];
	
	NSMutableArray *flagArray=[[NSMutableArray alloc] initWithObjects:@"筹码1.png",@"筹码2.png",@"筹码3.png",@"筹码4.png",@"筹码5.png",
							   @"筹码6.png",@"筹码7.png",@"筹码8.png",nil];
	
	int flagNum = 0;
	
#if 0	
	for (int i=0; i < nTotalPlayer; i++)
	{
		int cardNum=[[sortArray objectAtIndex:nTotalPlayer - i - 1] intValue];
		
		NSString *name= [dir objectForKey:[NSNumber numberWithInt:cardNum]];//[NSString stringWithFormat:@"%d",cardNum]];
		
		NSLog(@"cardNum=%d, name=%@",cardNum,name);

		CCSprite *spCellBg=[CCSprite spriteWithFile:@"人物框.png"];
		spCellBg.position=ccp(size.width/2 , 390 - 70 * i );
		[self addChild:spCellBg];

		CCMenuItem *spFlag;
		CCMenuItemFont *Player;
		CCMenuItem *spNum;
		CCMenuItem *spTextPoint;
		
		if (i==0)
		{
			spFlag = [CCMenuItemImage itemFromNormalImage:@"奖牌.png" selectedImage:@"奖牌.png"];
			//Player = [CCMenuItemFont itemFromString:[NSString stringWithFormat:@"%@  %d点",name,cardNum/4+2]];
			
		}
		else if(i==nTotalPlayer-1)
		{
			spFlag = [CCMenuItemImage itemFromNormalImage:@"骷髅.png" selectedImage:@"骷髅.png"];
			//Player = [CCMenuItemFont itemFromString:[NSString stringWithFormat:@"%@  %d点",name,cardNum/4+2]];
		}
		else
		{
			flagNum = arc4random()%[flagArray count];
			spFlag = [CCMenuItemImage itemFromNormalImage:[flagArray objectAtIndex:flagNum] selectedImage:[flagArray objectAtIndex:flagNum]];
			
			[flagArray removeObjectAtIndex:flagNum];
			//Player = [CCMenuItemFont itemFromString:[NSString stringWithFormat:@"%@  %d点",name,cardNum/4+2]];
		}
		
		if(cardNum>52)
		{
			Player = [CCMenuItemFont itemFromString:[NSString stringWithFormat:@"%@",name]];
			spNum = [CCMenuItemImage itemFromNormalImage:[NSString stringWithFormat:@"Cardnum_%d.png",14+(cardNum-52)] 
											selectedImage:[NSString stringWithFormat:@"Cardnum_%d.png",14+(cardNum-52)]];
		}
		else 
		{
			//Player = [CCMenuItemFont itemFromString:[NSString stringWithFormat:@"%@  %d点",name,cardNum/4+2]];
	
			Player = [CCMenuItemFont itemFromString:[NSString stringWithFormat:@"%@",name]];
			spNum = [CCMenuItemImage itemFromNormalImage:[NSString stringWithFormat:@"Cardnum_%d.png",(cardNum - 1)/4+2] 
											selectedImage:[NSString stringWithFormat:@"Cardnum_%d.png",(cardNum - 1)/4+2]];
		}

		//
		spTextPoint = [CCMenuItemImage itemFromNormalImage:@"点.png" selectedImage:@"点.png"];
		
		spFlag.position      = ccp(100-4,0);
		Player.position      = ccp(144,0);
		spNum.position       = ccp(200,0);
		spTextPoint.position = ccp(230,0);
		
		CCMenu *menu = [CCMenu menuWithItems:spFlag, Player,spNum,spTextPoint,nil];
		menu.position = ccp(0,390 - 70 * i);
		[self addChild:menu];
	}
#endif	
	
	[m_pScrollView setHidden:NO];
	
	for (int i=0; i < nTotalPlayer; i++)
	{
		int cardNum=[[sortArray objectAtIndex:nTotalPlayer - i - 1] intValue];
		
		NSString *name= [dir objectForKey:[NSNumber numberWithInt:cardNum]];//[NSString stringWithFormat:@"%d",cardNum]];
		
		NSLog(@"cardNum=%d, name=%@",cardNum,name);
		
		NSString * spFlag = nil;
		NSString * Player = nil;
		NSString * spNum  = nil;

		if (i==0)
		{
			spFlag = @"奖牌.png";
		}
		else if(i == nTotalPlayer - 1)
		{
			spFlag = @"骷髅.png";
		}
		else
		{
			flagNum = arc4random()%[flagArray count];
			spFlag  = [flagArray objectAtIndex:flagNum];
			
			[flagArray removeObjectAtIndex:flagNum];
		}
		
		if(cardNum > 52)
		{
			Player = [NSString stringWithFormat:@"%@",name];
			spNum  = [NSString stringWithFormat:@"Cardnum_%d.png",14+(cardNum-52)];
		}
		else 
		{
			Player = [NSString stringWithFormat:@"%@",name];
			spNum  = [NSString stringWithFormat:@"Cardnum_%d.png",(cardNum - 1)/4+2];
		}
		
		RecordItem * pRecordItem = [[RecordItem alloc] initRecord:Player RecordFlag:spFlag RecordNum:spNum frame:CGRectMake(65, 70 * i, 191, 62)];
		
		[m_pScrollView addSubview:pRecordItem];
		
		[pRecordItem release];
		
	}
	
	[m_pScrollView setContentSize:CGSizeMake(320, 70 * nTotalPlayer)];
	
	[dir release];
}

//获取玩家信息
-(void)getPlayerInfo
{
	NSArray  * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString * documentsDirectory = [paths objectAtIndex:0];
	NSString * filePath = [documentsDirectory stringByAppendingPathComponent:@"CardPlayer"];
	
	NSLog(@"filePath[%@]",filePath);
	
	NSDictionary * prefs = [NSDictionary dictionaryWithContentsOfFile:filePath];
	
	playerNameArray = [[NSMutableArray alloc] init];
	
	if(prefs)
	{
		int count = [prefs allKeys].count;
		NSLog(@"\n count   = %d",[prefs allKeys].count);
		//nTotalPlayer = [prefs allKeys].count;
		
		if(count > 0)
		{

			for (int i=0; i<count; i++)
			{
				[playerNameArray addObject:[[prefs objectForKey:[NSString stringWithFormat:@"Player_%d",i]] objectForKey:@"name"]];
				NSLog(@"Player:%@",[[prefs objectForKey:[NSString stringWithFormat:@"Player_%d",i]] objectForKey:@"name"]);
				//NSLog(@"allkey:%@",[prefs objectForKey:sub]);
			}

		}
	}
	
}

#pragma mark Logic
-(void)nextCard
{
	//[self playMusic:@"翻牌声音" loopNum:0 index:MUSIC_FANPAI];
	
	if(isResultView == YES)
	{
		return;
	}
	
	[SimpleAudioEngine sharedEngine].effectsVolume = 1.0f;
	
	[[SimpleAudioEngine sharedEngine] playEffect:@"card.caf"];
	
	//[self doubleMusicPlay:@"按钮效果音（按下）.mp3"];
	
	//isGameOver = YES;
	
//	if (nLeftSeconds!=10) {
//		[self unschedule:@selector(nextCard)];
//	}
	
	int index = 0;
	//while (nCurCardNum-1 != (index=arc4random()%[cardArray count]))
	while (nCurCardNum != (index=[(NSNumber*)[cardArray objectAtIndex:arc4random()%[cardArray count]] intValue]))
	{
		nCurCardNum = index;
		
		//[self spriteSetTexture:spCard ImageFile:[NSString stringWithFormat:@"%d.png",nCurCardNum]];
		[self spriteSetTexture:spNextCard ImageFile:[NSString stringWithFormat:@"%d.png",nCurCardNum]];
		isStart = YES;
		[self schedule:@selector(leftIn) interval:0.03f];
		break;
	}
}

//点击切换效果
-(void)leftIn//:(CGPoint*)pos
{

	CGPoint spPoint=[spCard position];
	CGRect rc= [spCard boundingBox];
	
	
	if(isStart)
	{
		//posX=rc.origin.x+rc.size.width-10;
		posX = SCREEN_WIDTH+rc.size.width/2;
		isStart = NO;
	}
	else
	{
		posX -= CARD_MOVE_STEP;
	}
	NSLog(@"Center=%d,posX=%d",spPoint.x,posX);
	
	int posY = spPoint.y;
	//int dis=rc.origin.x+rc.size.width-posX;
	
	//if (dis>0 && posX-spPoint.x)
	if (posX-SCREEN_WIDTH/2 > CARD_MOVE_STEP)
	{
		//[self spriteSetTexture:spCard ImageFile:@"card_back.png"];
		[spCard setPosition:ccp(spPoint.x-CARD_MOVE_STEP,posY)];
		
		[spImage setTexture:spNextCard.texture];
		//[spImage setTextureRect:CGRectMake(0 ,0, dis*2, rc.size.height)];//CGRectMake(posX-dis,rc.origin.y , dis*2, rc.size.height)
		[spImage setTextureRect:CGRectMake(0 ,0, rc.size.width, rc.size.height)];
		[spImage setPosition:ccp(posX,posY)];
		spImage.visible = YES;
	}
	else
	//if (posX-spPoint.x <10) //移动结束
	{
		[self spriteSetTexture:spCard ImageFile:[NSString stringWithFormat:@"%d.png",nCurCardNum]];
		[spCard setPosition:ccp(SCREEN_WIDTH/2,posY)];
		spImage.visible = NO;
		[self unschedule:@selector(leftIn)];
	}
}

-(void)OnNextStep:(id)sender
{
	[m_pScrollView removeFromSuperview];
	
	if(delegate)
	{
		[delegate Card_GameSelected:ECard_Game_Next];
	}
}

-(void)Card_Game_Return:(id)sender
{
	[m_pScrollView removeFromSuperview];
	
	if(delegate)
	{
		[delegate Card_GameSelected:ECard_Game_Return];
	}
}

#pragma mark Touch
-(void) registerWithTouchDispatcher
{
	[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
}

-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
	if (isGameOver) //游戏结束
	{
		return NO;
	}
	//检测Crad 
	if([self isSpriteTouched:touch tag:CARD_GAME_SP_CARD])
	{
//		if (nLeftSeconds==10) {
//			[self nextCard];
//		}
//		else
//			[self schedule:@selector(nextCard) interval:0.8f];
		NSLog(@"isCardBack = %d",isCardBack);
		if (isCardBack) 
		{
			[self startSelectCard];
			isCardBack = NO;
			
		}
		else
			[self nextCard];
		
		return YES;
	}
	
	
	return NO;
}

//检查精灵是否被触摸
-(BOOL)isSpriteTouched:(UITouch *)touch tag:(uint)tagSprite
{
    CCSprite *sp=(CCSprite * )([self getChildByTag:tagSprite]);
	
	CGPoint point=[self convertTouchToNodeSpace:touch];
	
	CGRect rc=[sp boundingBox];
	
	if(rc.size.width <= 0.0001f || rc.size.height <= 0.0001f)
		return NO;
	
	if( CGRectContainsPoint(rc, point))
		return YES;
	else
		return NO;
	
}

//改变精灵的图片,不能改变大小
-(void)spriteSetTexture:(CCSprite * )sp ImageFile:(NSString * )imageName
{
	UIImage * image = [UIImage imageNamed: imageName];
	
	CCTexture2D * win = [ [CCTexture2D alloc] initWithImage:image];
	
	[sp setTexture:win];
	
	[win release];
}

- (void)layerReplaced
{
	
}

-(void)Card_Game_Des:(id)sender
{
	[m_pScrollView setHidden:YES];
	
	if(delegate)
	{
		[delegate Card_GameSelected:ECard_Game_Des];
	}
}

@end
